// utils/request.js

const BASE_URL = 'http://localhost:8080'
const WHITE_LIST = ['/login', '/register','/course',] // 无需token的白名单

class Request {
  constructor() {
    this.interceptors = {
      request: [],
      response: []
    }
  }

  // 添加请求拦截器
  useRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor)
  }

  // 添加响应拦截器
  useResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor)
  }

  // 核心请求方法
  async _request(method, url, data, config = {}) {
    const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`
    
    // 合并配置
    const mergedConfig = {
      header: {},
      timeout: 10000,
      ...config
    }

    // 执行请求拦截器
    let requestParams = { method, url: fullUrl, data, config: mergedConfig }
    for (const interceptor of this.interceptors.request) {
      requestParams = await interceptor(requestParams)
    }

    // 发送请求
    return new Promise((resolve, reject) => {
      wx.request({
        url: requestParams.url,
        method: requestParams.method,
        data: requestParams.data,
        header: requestParams.config.header,
        timeout: requestParams.config.timeout,
        success: async (res) => {
          // 执行响应拦截器
          let response = res
          for (const interceptor of this.interceptors.response) {
            response = await interceptor(response)
          }
          resolve(response.data)
        },
        fail: (error) => {
          this._handleError(error)
          reject(error)
        }
      })
    })
  }

  // GET请求
  get(url, params = {}, config) {
    return this._request('GET', url, params, config)
  }

  // POST请求
  post(url, data = {}, config) {
    return this._request('POST', url, data, config)
  }

  // 其他方法（PUT/DELETE等）
  put(url, data = {}, config) {
    return this._request('PUT', url, data, config)
  }

  delete(url, data = {}, config) {
    return this._request('DELETE', url, data, config)
  }

  // 错误处理
  _handleError(error) {
    console.error('Request Error:', error)
    wx.showToast({
      title: '网络请求失败，请重试',
      icon: 'none'
    })
  }
}

// 创建单例
const request = new Request()

// 全局配置拦截器 --------------------------------------------------
// 请求拦截器：添加Token
request.useRequestInterceptor(async (config) => {
  if (!WHITE_LIST.includes(config.url.replace(BASE_URL, ''))) {
    const token = wx.getStorageSync('token')
    if (token) {
      config.config.header['Authorization'] = `Bearer ${token}`
    }
  }
  return config
})

// 响应拦截器：处理401状态码
request.useResponseInterceptor(async (response) => {
  if (response.statusCode === 401) {
    wx.showModal({
      title: '提示',
      content: '登录已过期，请重新登录',
      success: () => {
        wx.navigateTo({ url: '/pages/login/index' })
      }
    })
    throw new Error('登录过期')
  }

  if (response.data.code !== 200) {
    wx.showToast({
      title: response.data.message || '请求失败',
      icon: 'none'
    })
  }
  return response
})

export default request

